package service

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonmodels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/services"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"

	"gorm.io/gorm"
)

// AccountService 账号服务
type AccountService struct {
	db *gorm.DB
}

// NewAccountService 创建账号服务实例
func NewAccountService() *AccountService {
	return &AccountService{
		db: database.DB,
	}
}

// CreateMasterAccount 创建主账号
func (s *AccountService) CreateMasterAccount(userID int64, accountName, accountType string) (*models.MasterAccount, error) {
	// 检查用户是否已有主账号
	var existingAccount models.MasterAccount
	if err := s.db.Where("user_id = ?", userID).First(&existingAccount).Error; err == nil {
		return nil, errors.New("用户已存在主账号")
	}

	// 创建主账号
	masterAccount := &models.MasterAccount{
		UserID:         userID,
		AccountName:    accountName,
		AccountType:    accountType,
		Status:         "active",
		MaxSubAccounts: 10,
	}

	if err := s.db.Create(masterAccount).Error; err != nil {
		return nil, fmt.Errorf("创建主账号失败: %v", err)
	}

	return masterAccount, nil
}

// GetMasterAccount 获取主账号信息
func (s *AccountService) GetMasterAccount(userID int64) (*models.MasterAccount, error) {
	var account models.MasterAccount
	if err := s.db.Where("user_id = ?", userID).First(&account).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("account not found")
		}
		return nil, err
	}
	return &account, nil
}

// UpdateMasterAccount 更新主账号信息
func (s *AccountService) UpdateMasterAccount(account *models.MasterAccount) error {
	// 验证必填字段
	if account.ID == 0 {
		return fmt.Errorf("account id is required")
	}

	// 检查账户是否存在
	var existingAccount models.MasterAccount
	if err := s.db.First(&existingAccount, account.ID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("account not found")
		}
		return err
	}

	// 更新账户信息
	updates := map[string]interface{}{
		"status":     account.Status,
		"updated_at": time.Now(),
	}

	if account.AccountName != "" {
		updates["account_name"] = account.AccountName
	}

	if account.AccountType != "" {
		updates["account_type"] = account.AccountType
	}

	if account.MaxSubAccounts > 0 {
		updates["max_sub_accounts"] = account.MaxSubAccounts
	}

	if err := s.db.Model(&existingAccount).Updates(updates).Error; err != nil {
		return fmt.Errorf("failed to update account: %v", err)
	}

	return nil
}

// CreateSubAccount 创建子账号
func (s *AccountService) CreateSubAccount(masterAccountID int64, userID int64, accountName, role string, permissions string) (*models.SubAccount, error) {
	// 检查主账号是否存在且状态正常
	var masterAccount models.MasterAccount
	if err := s.db.First(&masterAccount, masterAccountID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("主账号不存在")
		}
		return nil, fmt.Errorf("获取主账号失败: %v", err)
	}

	if !masterAccount.IsActive() {
		return nil, errors.New("主账号状态异常")
	}

	// 检查子账号数量是否超限
	var subAccountCount int64
	if err := s.db.Model(&models.SubAccount{}).Where("master_account_id = ?", masterAccountID).Count(&subAccountCount).Error; err != nil {
		return nil, fmt.Errorf("检查子账号数量失败: %v", err)
	}

	if !masterAccount.CanCreateSubAccount(int(subAccountCount)) {
		return nil, errors.New("子账号数量已达上限")
	}

	// 创建子账号
	subAccount := &models.SubAccount{
		MasterAccountID: masterAccountID,
		UserID:          userID,
		AccountName:     accountName,
		Role:            role,
		Permissions:     permissions,
		Status:          "active",
		LastLoginTime:   nil,
		LastLoginIP:     "",
	}

	if err := s.db.Create(subAccount).Error; err != nil {
		return nil, fmt.Errorf("创建子账号失败: %v", err)
	}

	return subAccount, nil
}

// GetSubAccount 获取子账号信息
func (s *AccountService) GetSubAccount(id int64) (*models.SubAccount, error) {
	var subAccount models.SubAccount
	if err := s.db.First(&subAccount, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("子账号不存在")
		}
		return nil, fmt.Errorf("获取子账号失败: %v", err)
	}
	return &subAccount, nil
}

// UpdateSubAccount 更新子账号信息
func (s *AccountService) UpdateSubAccount(id int64, accountName, role string, permissions string) error {
	updates := map[string]interface{}{
		"account_name": accountName,
		"role":         role,
		"permissions":  permissions,
	}

	if err := s.db.Model(&models.SubAccount{}).Where("id = ?", id).Updates(updates).Error; err != nil {
		return fmt.Errorf("更新子账号失败: %v", err)
	}
	return nil
}

// DeleteSubAccount 删除子账号
func (s *AccountService) DeleteSubAccount(id int64) error {
	// 先检查子账号是否存在
	var subAccount models.SubAccount
	if err := s.db.First(&subAccount, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return fmt.Errorf("sub_account_not_found")
		}
		return fmt.Errorf("查询子账号失败: %v", err)
	}

	// 执行删除操作
	if err := s.db.Delete(&subAccount).Error; err != nil {
		return fmt.Errorf("delete_sub_account_failed: %v", err)
	}
	return nil
}

// UpdateSubAccountStatus 更新子账号状态
func (s *AccountService) UpdateSubAccountStatus(id int64, status string) error {
	// 先检查子账号是否存在
	var subAccount models.SubAccount
	if err := s.db.First(&subAccount, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return fmt.Errorf("sub_account_not_found")
		}
		return fmt.Errorf("query_sub_account_failed: %v", err)
	}

	// 验证状态值是否有效
	validStatuses := map[string]bool{
		"active":   true,
		"inactive": true,
		"frozen":   true,
	}
	if !validStatuses[status] {
		return fmt.Errorf("invalid_status")
	}

	// 执行更新操作
	if err := s.db.Model(&subAccount).Update("status", status).Error; err != nil {
		return fmt.Errorf("update_sub_account_status_failed: %v", err)
	}
	return nil
}

// UpdateSubAccountLoginInfo 更新子账号登录信息
func (s *AccountService) UpdateSubAccountLoginInfo(id int64, ip string) error {
	// 先检查子账号是否存在
	var subAccount models.SubAccount
	if err := s.db.First(&subAccount, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return fmt.Errorf("sub_account_not_found")
		}
		return fmt.Errorf("query_sub_account_failed: %v", err)
	}

	updates := map[string]interface{}{
		"last_login_time": time.Now(),
		"last_login_ip":   ip,
	}

	if err := s.db.Model(&subAccount).Updates(updates).Error; err != nil {
		return fmt.Errorf("update_sub_account_login_info_failed: %v", err)
	}
	return nil
}

// GetSubAccountsByMasterID 获取主账号下的所有子账号
func (s *AccountService) GetSubAccountsByMasterID(masterAccountID int64) ([]models.SubAccount, error) {
	// 先检查主账号是否存在
	var masterAccount models.MasterAccount
	fmt.Println("masterAccountID", masterAccountID)
	if err := s.db.First(&masterAccount, masterAccountID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, fmt.Errorf("master_account_not_found")
		}
		return nil, fmt.Errorf("query_master_account_failed: %v", err)
	}

	var subAccounts []models.SubAccount
	if err := s.db.Where("master_account_id = ?", masterAccountID).Find(&subAccounts).Error; err != nil {
		return nil, fmt.Errorf("get_sub_accounts_failed: %v", err)
	}
	return subAccounts, nil
}

// ValidateSubAccountPermission 验证子账号权限
func (s *AccountService) ValidateSubAccountPermission(subAccountID int64, requiredPermission string) (bool, error) {
	var subAccount models.SubAccount
	if err := s.db.First(&subAccount, subAccountID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return false, fmt.Errorf("sub_account_not_found")
		}
		return false, fmt.Errorf("query_sub_account_failed: %v", err)
	}

	// 如果是管理员角色，直接返回true
	if subAccount.Role == "admin" {
		return true, nil
	}

	// 解析权限JSON
	permissions, err := common.ParseJSONToMap(subAccount.Permissions)
	if err != nil {
		return false, fmt.Errorf("parse_permissions_failed: %v", err)
	}

	// 检查是否具有所需权限
	hasPermission, exists := permissions[requiredPermission]
	return exists && hasPermission.(bool), nil
}

// GetMasterAccountByUserID 根据用户ID获取主账号信息
func (s *AccountService) GetMasterAccountByUserID(userID int64) (*models.MasterAccount, error) {
	var masterAccount models.MasterAccount
	if err := s.db.Where("user_id = ?", userID).First(&masterAccount).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, fmt.Errorf("master_account_not_found")
		}
		return nil, fmt.Errorf("query_master_account_failed: %v", err)
	}
	return &masterAccount, nil
}

// GenerateInvitationCode 生成子账号邀请码
func (s *AccountService) GenerateInvitationCode(userID int64, accountName, role string, permissions map[string]interface{}, expiresIn time.Duration) (string, error) {
	// 检查主账号是否存在且状态正常
	var masterAccount models.MasterAccount
	if err := s.db.Where("user_id = ?", userID).First(&masterAccount).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return "", fmt.Errorf("master_account_not_found")
		}
		return "", fmt.Errorf("query_master_account_failed: %v", err)
	}

	if !masterAccount.IsActive() {
		return "", fmt.Errorf("master_account_inactive")
	}

	// 生成8位随机邀请码
	invitationCode := common.GenerateRandomString(8)

	// 准备存储的数据
	invitationData := map[string]interface{}{
		"user_id":      userID,
		"account_name": accountName,
		"role":         role,
		"permissions":  permissions,
	}

	// 将数据序列化为JSON
	jsonData, err := json.Marshal(invitationData)
	if err != nil {
		return "", fmt.Errorf("serialize_invitation_data_failed: %v", err)
	}

	// 将邀请码信息存储到Redis，设置过期时间
	ctx := context.Background()
	key := fmt.Sprintf("invitation:code:%s", invitationCode)
	err = database.RedisClient.Set(ctx, key, jsonData, expiresIn).Err()
	if err != nil {
		return "", fmt.Errorf("store_invitation_code_failed: %v", err)
	}

	return invitationCode, nil
}

func (s *AccountService) ListMasterAccounts(page, pageSize int) ([]models.MasterAccount, int64, error) {
	var accounts []models.MasterAccount
	var total int64

	// 获取总数
	if err := s.db.Model(&models.MasterAccount{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * pageSize
	if err := s.db.Offset(offset).Limit(pageSize).Find(&accounts).Error; err != nil {
		return nil, 0, err
	}

	return accounts, total, nil
}

func (s *AccountService) DeleteMasterAccount(matrixAccount string) error {
	result := s.db.Where("matrix_account = ?", matrixAccount).Delete(&models.MasterAccount{})
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return fmt.Errorf("account not found")
	}
	return nil
}

// AllocateBalance 划拨资金
func (s *AccountService) AllocateBalance(masterAccountID, subAccountID int64, amount float64, remark string, fundType string) error {
	// 将 float64 转换为 decimal.Decimal
	amountDecimal := decimal.NewFromFloat(amount)

	return s.db.Transaction(func(tx *gorm.DB) error {
		var master models.MasterAccount
		if err := tx.First(&master, masterAccountID).Error; err != nil {
			return err
		}
		var sub models.SubAccount
		if err := tx.First(&sub, subAccountID).Error; err != nil {
			return err
		}

		// 判断是划拨还是退回
		isRefund := amountDecimal.LessThan(decimal.Zero)
		absAmount := amountDecimal.Abs()

		// 检查余额是否足够
		if isRefund {
			// 退回时检查子账户余额
			if sub.Balance.LessThan(absAmount) {
				return fmt.Errorf("insufficient_sub_balance")
			}
		} else {
			// 划拨时检查主账户余额
			if master.Balance.LessThan(absAmount) {
				return fmt.Errorf("insufficient_master_balance")
			}
		}

		// 使用 SELECT FOR UPDATE 锁定记录，防止并发更新
		if err := tx.Set("gorm:query_option", "FOR UPDATE").First(&master, masterAccountID).Error; err != nil {
			return err
		}
		if err := tx.Set("gorm:query_option", "FOR UPDATE").First(&sub, subAccountID).Error; err != nil {
			return err
		}

		// 再次检查余额（在锁定的情况下）
		if isRefund {
			if sub.Balance.LessThan(absAmount) {
				return fmt.Errorf("insufficient_sub_balance")
			}
		} else {
			if master.Balance.LessThan(absAmount) {
				return fmt.Errorf("insufficient_master_balance")
			}
		}

		// 更新主账户余额（主账户减少，子账户增加）
		if err := tx.Model(&master).Update("balance", gorm.Expr("balance - ?", amountDecimal)).Error; err != nil {
			return err
		}

		// 更新子账户余额
		if err := tx.Model(&sub).Update("balance", gorm.Expr("balance + ?", amountDecimal)).Error; err != nil {
			return err
		}

		// 更新用户矩阵账户的总转账金额
		if err := tx.Model(&models.UserMatrixAccount{}).
			Where("user_id = ? AND status = 'active'", sub.UserID).
			Update("total_transfer_amount", gorm.Expr("total_transfer_amount + ?", amount)).Error; err != nil {
			return err
		}

		// 记录划拨流水
		fund := &models.MasterSubAccountFund{
			MasterAccountID: masterAccountID,
			SubAccountID:    subAccountID,
			Amount:          amountDecimal,
			Type:            fundType,
			Remark:          remark,
		}
		if err := tx.Create(fund).Error; err != nil {
			return err
		}
		return nil
	})
}

func (s *AccountService) SubAccountConsume(subAccountID int64, amount float64, remark string) error {
	// 将 float64 转换为 decimal.Decimal
	amountDecimal := decimal.NewFromFloat(amount)

	return s.db.Transaction(func(tx *gorm.DB) error {
		var sub models.SubAccount
		if err := tx.First(&sub, subAccountID).Error; err != nil {
			return err
		}

		// 使用 SELECT FOR UPDATE 锁定记录，防止并发更新
		if err := tx.Set("gorm:query_option", "FOR UPDATE").First(&sub, subAccountID).Error; err != nil {
			return err
		}

		if sub.Balance.LessThan(amountDecimal) {
			return fmt.Errorf("insufficient_sub_balance")
		}
		if err := tx.Model(&sub).Update("balance", gorm.Expr("balance - ?", amountDecimal)).Error; err != nil {
			return err
		}
		orderID := common.GenerateRandomString(16)
		// 新增：插入消费记录
		record := models.SubAccountConsumeRecord{
			SubAccountID: subAccountID,
			Amount:       amountDecimal,
			Type:         "consume",
			Remark:       remark,
			OrderID:      orderID,
			Status:       "success",
		}
		if err := tx.Create(&record).Error; err != nil {
			return err
		}
		return nil
	})
}

func (s *AccountService) RefundAndDeleteSubAccount(masterAccountID, subAccountID int64, remark string) error {
	return s.db.Transaction(func(tx *gorm.DB) error {
		var sub models.SubAccount
		if err := tx.First(&sub, subAccountID).Error; err != nil {
			return err
		}
		refundAmount := sub.Balance
		if refundAmount.GreaterThan(decimal.Zero) {
			if err := tx.Model(&models.MasterAccount{}).Where("id = ?", masterAccountID).
				Update("balance", gorm.Expr("balance + ?", refundAmount)).Error; err != nil {
				return err
			}

			// 更新用户矩阵账户的总转账金额（退款时减少）
			if err := tx.Model(&models.UserMatrixAccount{}).
				Where("user_id = ? AND status = 'active'", sub.UserID).
				Update("total_transfer_amount", gorm.Expr("total_transfer_amount - ?", refundAmount)).Error; err != nil {
				return err
			}

			fund := models.MasterSubAccountFund{
				MasterAccountID: masterAccountID,
				SubAccountID:    subAccountID,
				Amount:          refundAmount.Neg(),
				Type:            "refund",
				Remark:          remark,
			}
			if err := tx.Create(&fund).Error; err != nil {
				return err
			}
		}
		if err := tx.Delete(&sub).Error; err != nil {
			return err
		}
		return nil
	})
}

// GetMasterSubAccountFunds 获取主账号资金划拨明细
func (s *AccountService) GetMasterSubAccountFunds(masterAccountID int64, page, pageSize int, queryType string, subID int64, subAccountName string, createdAtStart string, createdAtEnd string) ([]models.MasterSubAccountFundWithSubAccount, int64, error) {
	var funds []models.MasterSubAccountFundWithSubAccount
	var total int64

	// 构建查询，关联子账号表获取account_name
	query := s.db.Table("master_sub_account_funds").
		Select("master_sub_account_funds.*, sub_accounts.account_name as sub_account_name").
		Joins("LEFT JOIN sub_accounts ON master_sub_account_funds.sub_account_id = sub_accounts.id").
		Where("master_sub_account_funds.master_account_id = ?", masterAccountID)

	// 如果指定了子账号ID，添加子账号过滤条件
	if subID > 0 {
		query = query.Where("master_sub_account_funds.sub_account_id = ?", subID)
	}

	// 如果指定了子账号名称，添加模糊查询条件
	if subAccountName != "" {
		query = query.Where("sub_accounts.account_name LIKE ?", "%"+subAccountName+"%")
	}

	// 根据查询类型添加过滤条件
	switch queryType {
	case "IN":
		query = query.Where("master_sub_account_funds.amount > 0")
	case "OUT":
		query = query.Where("master_sub_account_funds.amount < 0")
	case "allocate":
		query = query.Where("master_sub_account_funds.type = ?", "allocate")
	case "refund":
		query = query.Where("master_sub_account_funds.type = ?", "refund")
	default:
		// 如果type不是预定义的值，直接按type字段查询
		if queryType != "" {
			query = query.Where("master_sub_account_funds.type = ?", queryType)
		}
	}

	// 处理时间范围查询
	if createdAtStart != "" {
		query = query.Where("master_sub_account_funds.created_at >= ?", createdAtStart)
	}
	if createdAtEnd != "" {
		query = query.Where("master_sub_account_funds.created_at <= ?", createdAtEnd)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, fmt.Errorf("count_funds_failed: %v", err)
	}

	// 分页查询
	offset := (page - 1) * pageSize
	if err := query.Order("master_sub_account_funds.created_at DESC").
		Offset(offset).
		Limit(pageSize).
		Find(&funds).Error; err != nil {
		return nil, 0, fmt.Errorf("get_funds_failed: %v", err)
	}

	return funds, total, nil
}

// GetSubAccountConsumeRecords 获取子账号消费记录
func (s *AccountService) GetSubAccountConsumeRecords(subAccountID int64, page, pageSize int) ([]models.SubAccountConsumeRecord, int64, error) {
	var records []models.SubAccountConsumeRecord
	var total int64

	// 获取总数
	if err := s.db.Model(&models.SubAccountConsumeRecord{}).
		Where("sub_account_id = ?", subAccountID).
		Count(&total).Error; err != nil {
		return nil, 0, fmt.Errorf("count_records_failed: %v", err)
	}

	// 分页查询
	offset := (page - 1) * pageSize
	if err := s.db.Where("sub_account_id = ?", subAccountID).
		Order("created_at DESC").
		Offset(offset).
		Limit(pageSize).
		Find(&records).Error; err != nil {
		return nil, 0, fmt.Errorf("get_records_failed: %v", err)
	}

	return records, total, nil
}

// AdjustAccountBalanceByRole 根据用户角色扣减/退还主/子账户余额
func AdjustAccountBalanceByRole(tx *gorm.DB, roleID int64, userID int64, amount float64) error {
	amountDecimal := decimal.NewFromFloat(amount)

	switch roleID {
	case 1, 2, 3: // 普通用户、管理员、主账号都使用主账号表
		// 先检查余额是否足够
		var masterAccount models.MasterAccount
		if err := tx.Set("gorm:query_option", "FOR UPDATE").Where("user_id = ?", userID).First(&masterAccount).Error; err != nil {
			return err
		}
		if masterAccount.Balance.LessThan(amountDecimal) {
			return fmt.Errorf("insufficient_master_balance")
		}
		return tx.Model(&models.MasterAccount{}).
			Where("user_id = ?", userID).
			Update("balance", gorm.Expr("balance - ?", amountDecimal)).Error
	case 5: // 子账号
		// 先检查余额是否足够
		var subAccount models.SubAccount
		if err := tx.Set("gorm:query_option", "FOR UPDATE").Where("user_id = ?", userID).First(&subAccount).Error; err != nil {
			return err
		}
		if subAccount.Balance.LessThan(amountDecimal) {
			return fmt.Errorf("insufficient_sub_balance")
		}
		return tx.Model(&models.SubAccount{}).
			Where("user_id = ?", userID).
			Update("balance", gorm.Expr("balance - ?", amountDecimal)).Error
	default:
		// 对于其他角色，也使用主账号表（保持向后兼容）
		var masterAccount models.MasterAccount
		if err := tx.Set("gorm:query_option", "FOR UPDATE").Where("user_id = ?", userID).First(&masterAccount).Error; err != nil {
			return err
		}
		if masterAccount.Balance.LessThan(amountDecimal) {
			return fmt.Errorf("insufficient_master_balance")
		}
		return tx.Model(&models.MasterAccount{}).
			Where("user_id = ?", userID).
			Update("balance", gorm.Expr("balance - ?", amountDecimal)).Error
	}
}

// GetDB 获取数据库连接
func GetDB() *gorm.DB {
	return database.DB
}

// SyncPhotonPayBalance 同步光子易余额
func SyncPhotonPayBalance(ctx *gin.Context, db *gorm.DB, photonPayClient *photonpay.PhotonPayClient, userID int64, masterAccountID int64) {
	// 使用事务确保数据一致性
	err := db.Transaction(func(tx *gorm.DB) error {
		var userMatrixAccount models.UserMatrixAccount
		if err := tx.Model(&models.UserMatrixAccount{}).Where("user_id = ?", userID).First(&userMatrixAccount).Error; err != nil {
			log.Printf("主账号[%d]同步光子易余额失败：找不到矩阵账户: %v", masterAccountID, err)
			return err
		}

		params := photonmodels.AccountListQueryParams{
			MatrixAccount: userMatrixAccount.MatrixAccount,
		}
		result, err := services.GetAccountList(ctx, photonPayClient, params)
		if err != nil {
			log.Printf("主账号[%d]同步光子易余额失败：获取账户列表失败: %v", masterAccountID, err)
			return err
		}

		if result == nil || len(result.Data) == 0 {
			log.Printf("主账号[%d]同步光子易余额失败：账户列表为空", masterAccountID)
			return fmt.Errorf("account list is empty")
		}

		for _, account := range result.Data {
			if account.Currency == "USD" {
				// 添加余额上限检查，防止同步异常巨大的余额
				if account.RealTimeBalance > 1000000 {
					log.Printf("警告：主账号[%d]同步光子易余额异常巨大: %.2f，跳过同步", masterAccountID, account.RealTimeBalance)
					return fmt.Errorf("abnormal balance amount: %.2f", account.RealTimeBalance)
				}

				// 获取当前主账号余额
				var currentMasterAccount models.MasterAccount
				if err := tx.Where("id = ?", masterAccountID).First(&currentMasterAccount).Error; err != nil {
					log.Printf("主账号[%d]同步光子易余额失败：查询当前余额失败: %v", masterAccountID, err)
					return err
				}

				// 检查余额差异是否过大
				balanceDiff := currentMasterAccount.Balance.Sub(decimal.NewFromFloat(account.RealTimeBalance)).Abs()
				if balanceDiff.GreaterThan(decimal.NewFromFloat(1000000)) {
					log.Printf("警告：主账号[%d]余额差异过大，当前余额=%s, 同步余额=%.2f, 差异=%s，跳过同步",
						masterAccountID, currentMasterAccount.Balance.String(), account.RealTimeBalance, balanceDiff.String())
					return fmt.Errorf("balance difference too large: %s", balanceDiff.String())
				}

				// 使用事务更新余额
				balanceDecimal := decimal.NewFromFloat(account.RealTimeBalance)
				if err := tx.Model(&models.MasterAccount{}).
					Where("id = ?", masterAccountID).
					Update("balance", balanceDecimal).Error; err != nil {
					log.Printf("主账号[%d]同步光子易余额失败：更新余额失败: %v", masterAccountID, err)
					return err
				}
				log.Printf("主账号[%d]创建后同步光子易余额成功: %s", masterAccountID, balanceDecimal.String())
				return nil
			}
		}

		log.Printf("主账号[%d]同步光子易余额失败：未找到USD账户", masterAccountID)
		return fmt.Errorf("USD account not found")
	})

	if err != nil {
		log.Printf("主账号[%d]同步光子易余额失败: %v", masterAccountID, err)
	}
}

// GetSubAccountsWithConditions 根据条件查询子账号
func (s *AccountService) GetSubAccountsWithConditions(masterAccountID int64, conditions map[string]interface{}, page, pageSize int) ([]models.SubAccountWithUser, int64, error) {
	// 先检查主账号是否存在
	var masterAccount models.MasterAccount
	if err := s.db.First(&masterAccount, masterAccountID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, 0, fmt.Errorf("master_account_not_found")
		}
		return nil, 0, fmt.Errorf("query_master_account_failed: %v", err)
	}

	// 构建查询
	query := s.db.Table("sub_accounts").
		Select("sub_accounts.*, users.username, users.email, users.phone, users.name").
		Joins("LEFT JOIN users ON sub_accounts.user_id = users.id").
		Where("sub_accounts.master_account_id = ?", masterAccountID)

	// 应用查询条件
	if username, exists := conditions["username"]; exists && username != "" {
		query = query.Where("users.username LIKE ?", "%"+username.(string)+"%")
	}

	if role, exists := conditions["role"]; exists && role != "" {
		query = query.Where("sub_accounts.role = ?", role)
	}

	if status, exists := conditions["status"]; exists && status != "" {
		query = query.Where("sub_accounts.status = ?", status)
	}

	if permissions, exists := conditions["permissions"]; exists && permissions != "" {
		// 使用JSON_CONTAINS查询权限
		query = query.Where("JSON_CONTAINS(sub_accounts.permissions, ?)", permissions)
	}

	// 获取总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, fmt.Errorf("count_sub_accounts_failed: %v", err)
	}

	// 分页查询
	offset := (page - 1) * pageSize
	var subAccounts []models.SubAccountWithUser
	if err := query.Offset(offset).Limit(pageSize).Order("sub_accounts.created_at DESC").Find(&subAccounts).Error; err != nil {
		return nil, 0, fmt.Errorf("get_sub_accounts_failed: %v", err)
	}

	return subAccounts, total, nil
}
